#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <fstream>
#include <mutex>
#include <unordered_map>
#include <boost/filesystem.hpp>
#include "util.hpp"

namespace ns_index{
    typedef struct DocInfo{
        std::string title;
        std::string contnet;
        std::string url;
        uint64_t doc_id;
    }DocInfo_t;

    typedef struct InvertedElem
    {
        uint64_t doc_id;
        std::string word;
        int weight;
    }InvertedElem;

    // 倒排拉链
    typedef std::vector<InvertedElem> InvertedList;

    class Index{
    private:
        // 正排索引, 数组下标即文档id
        std::vector<DocInfo_t> forward_index;
        // 倒排索引
        std::unordered_map<std::string, InvertedList> inverted_index;
    private:
        Index() {};
        Index(const Index&) = delete;
        Index& operator=(const Index&) = delete;

        static Index* instance;
        static std::mutex mtx;
    public:
        ~Index() {};
        // 单例模式
        static Index* GetInstance()
        {
            if(instance == nullptr)
            {
                mtx.lock();
                if(instance == nullptr)
                {
                    instance = new Index();
                }
                mtx.unlock();
            }
            return instance;
        }
        // 获取文档内容
        DocInfo* GetForwardIndex(uint64_t doc_id)
        {
            if(doc_id > forward_index.size())
            {
                std::cerr << "doc_id is out of range" << std::endl;
                return nullptr;
            }
            return &forward_index[doc_id];
        }
        // 根据关键词获取倒排拉链
        InvertedList* GetInvertedList(std::string word)
        {
            auto it = inverted_index.find(word);
            if(it == inverted_index.end())
            {
                std::cerr << "no InvertedList" << std::endl;
                return nullptr;
            }
            return &(it->second);
        }
        // 构建正排和倒排索引
        // raw.txt
        bool BuildIndex(const std::string& input)
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if(!in.is_open())
            {
                std::cerr << "sorry, " << input << "open error" << std::endl;
                return false;
            }
            std::string line;
            int cont = 0;
            while(std::getline(in, line)) // debug, 从in中读入, 而不是cin
            {
                DocInfo* doc = BuildForwardIndex(line);
                if(nullptr == doc)
                {
                    std::cerr << "build " << line << " error" << std::endl;
                    continue;
                }
                BuildInvertedIndex(*doc);
                cont++;
                if(cont % 50 == 0)
                {
                    std::cout << "当前已建立的索引文档: " << cont << std::endl;
                }
            }
            
            return true;
        }
    private:
        DocInfo* BuildForwardIndex(const std::string& line)
        {
            std::vector<std::string> results;
            std::string step = "\3";
            // 解析line
            ns_util::StringUtil::Split(line, &results, step);
            // 填充doc
            if(results.size() != 3)
            {
                std::cerr << "parse line error" << std::endl;
                return nullptr;
            }
            DocInfo doc;
            doc.title = results[0];
            doc.contnet = results[1];
            doc.url = results[2];
            doc.doc_id = forward_index.size();
            // 插入到正排索引
            forward_index.push_back(std::move(doc));
            return &forward_index.back();
        }
        bool BuildInvertedIndex(const DocInfo& doc)
        {
            // word -> 倒排拉链
            struct word_cnt{
                int title_cnt;
                int content_cnt;

                word_cnt():title_cnt(0), content_cnt(0) {}
            };
            std::unordered_map<std::string, word_cnt>  word_map;

            // title 分词
            std::vector<std::string> title_words;
            ns_util::JiebaUtil::CutString(doc.title, &title_words);
            // 词频统计
            for(std::string& s : title_words)
            {
                boost::to_lower(s);
                word_map[s].title_cnt++;
            }

            std::vector<std::string> content_words;
            ns_util::JiebaUtil::CutString(doc.contnet, &content_words);
            for(std::string& s : content_words)
            {
                boost::to_lower(s);
                word_map[s].content_cnt++;
            }

#define X 10
#define Y 1
            // 构建倒排拉链
            for(auto& word_pair : word_map)
            {
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                item.weight = X*word_pair.second.title_cnt + Y*word_pair.second.content_cnt;
                InvertedList& inverted_list = inverted_index[word_pair.first];
                inverted_list.push_back(std::move(item));
            }
            
            return true;
        }
    };
    Index* Index::instance = nullptr;
    std::mutex Index::mtx;
}